<template>
  <div class="api-example">
    <el-card header="Axios封装使用示例">
      <div class="example-section">
        <h3>基础API调用</h3>
        <el-space wrap>
          <el-button @click="testLogin" type="primary">测试登录</el-button>
          <el-button @click="testGetUserInfo">获取用户信息</el-button>
          <el-button @click="testGetAnnotations">获取标注列表</el-button>
        </el-space>
      </div>

      <div class="example-section">
        <h3>高级功能</h3>
        <el-space wrap>
          <el-button @click="testRetry" type="warning">重试请求</el-button>
          <el-button @click="testConcurrent" type="success">并发请求</el-button>
          <el-button @click="testConfirm" type="danger">确认请求</el-button>
        </el-space>
      </div>

      <div class="example-section">
        <h3>文件操作</h3>
        <el-space wrap>
          <el-upload
            :before-upload="handleUpload"
            :show-file-list="false"
            action="#"
          >
            <el-button type="primary">上传文件</el-button>
          </el-upload>
          <el-button @click="testDownload">下载文件</el-button>
        </el-space>
      </div>

      <div class="example-section">
        <h3>请求日志</h3>
        <el-scrollbar height="200px">
          <div class="log-container">
            <div 
              v-for="(log, index) in logs" 
              :key="index" 
              class="log-item"
              :class="log.type"
            >
              <span class="log-time">{{ log.time }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
          </div>
        </el-scrollbar>
        <el-button @click="clearLogs" size="small" style="margin-top: 10px;">清空日志</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { inject } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'ApiExample',
  setup() {
    // 注入HTTP工具
    const $http = inject('$http')
    const $api = inject('$api')
    const $request = inject('$request')

    return {
      $http,
      $api,
      $request
    }
  },
  data() {
    return {
      logs: []
    }
  },
  methods: {
    // 添加日志
    addLog(message, type = 'info') {
      this.logs.unshift({
        time: new Date().toLocaleTimeString(),
        message,
        type
      })
      
      // 限制日志数量
      if (this.logs.length > 50) {
        this.logs = this.logs.slice(0, 50)
      }
    },

    // 清空日志
    clearLogs() {
      this.logs = []
    },

    // 测试登录
    async testLogin() {
      try {
        this.addLog('开始测试登录...', 'info')
        
        // 模拟登录请求
        const result = await this.$request.post('/auth/login', {
          username: 'admin',
          password: '123456'
        }, {
          showSuccessMsg: true,
          loadingText: '登录中...'
        })
        
        this.addLog('登录成功: ' + JSON.stringify(result), 'success')
      } catch (error) {
        this.addLog('登录失败: ' + error.message, 'error')
      }
    },

    // 测试获取用户信息
    async testGetUserInfo() {
      try {
        this.addLog('开始获取用户信息...', 'info')
        
        const result = await this.$api.user.getUserInfo()
        
        this.addLog('获取用户信息成功: ' + JSON.stringify(result), 'success')
      } catch (error) {
        this.addLog('获取用户信息失败: ' + error.message, 'error')
      }
    },

    // 测试获取标注列表
    async testGetAnnotations() {
      try {
        this.addLog('开始获取标注列表...', 'info')
        
        const result = await this.$api.annotation.getList({
          page: 1,
          pageSize: 10
        })
        
        this.addLog('获取标注列表成功: ' + JSON.stringify(result), 'success')
      } catch (error) {
        this.addLog('获取标注列表失败: ' + error.message, 'error')
      }
    },

    // 测试重试请求
    async testRetry() {
      try {
        this.addLog('开始测试重试请求...', 'info')
        
        const result = await this.$http.retry(
          () => this.$request.get('/api/test-retry'),
          {
            maxRetries: 3,
            delay: 1000,
            showRetryMsg: true
          }
        )
        
        this.addLog('重试请求成功: ' + JSON.stringify(result), 'success')
      } catch (error) {
        this.addLog('重试请求失败: ' + error.message, 'error')
      }
    },

    // 测试并发请求
    async testConcurrent() {
      try {
        this.addLog('开始测试并发请求...', 'info')
        
        const results = await this.$http.concurrent([
          this.$api.user.getUserInfo(),
          this.$api.annotation.getList(),
          this.$api.common.healthCheck()
        ], {
          showLoading: true,
          loadingText: '并发请求中...'
        })
        
        this.addLog(`并发请求完成: 成功${results.success.length}个, 失败${results.errors.length}个`, 'success')
      } catch (error) {
        this.addLog('并发请求失败: ' + error.message, 'error')
      }
    },

    // 测试确认请求
    async testConfirm() {
      try {
        this.addLog('开始测试确认请求...', 'info')
        
        const result = await this.$http.confirmRequest(
          () => this.$request.delete('/api/test-delete'),
          {
            title: '删除确认',
            message: '这是一个测试删除操作，确定要继续吗？',
            type: 'warning'
          }
        )
        
        if (result) {
          this.addLog('确认请求成功: ' + JSON.stringify(result), 'success')
        } else {
          this.addLog('用户取消了操作', 'warning')
        }
      } catch (error) {
        this.addLog('确认请求失败: ' + error.message, 'error')
      }
    },

    // 测试文件上传
    async handleUpload(file) {
      try {
        this.addLog(`开始上传文件: ${file.name}`, 'info')
        
        const result = await this.$http.uploadWithProgress(file, {
          url: '/file/upload',
          showProgress: true,
          onProgress: (percent) => {
            this.addLog(`上传进度: ${percent}%`, 'info')
          }
        })
        
        this.addLog('文件上传成功: ' + JSON.stringify(result), 'success')
      } catch (error) {
        this.addLog('文件上传失败: ' + error.message, 'error')
      }
      
      return false // 阻止默认上传
    },

    // 测试文件下载
    async testDownload() {
      try {
        this.addLog('开始下载文件...', 'info')
        
        await this.$http.downloadFile('/file/download/test.pdf', 'test-file.pdf', {
          showProgress: true
        })
        
        this.addLog('文件下载成功', 'success')
      } catch (error) {
        this.addLog('文件下载失败: ' + error.message, 'error')
      }
    }
  }
}
</script>

<style scoped>
.api-example {
  padding: 20px;
}

.example-section {
  margin-bottom: 30px;
}

.example-section h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.log-container {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
}

.log-item {
  display: flex;
  margin-bottom: 5px;
  padding: 2px 0;
}

.log-time {
  color: #909399;
  margin-right: 10px;
  min-width: 80px;
}

.log-message {
  flex: 1;
  word-break: break-all;
}

.log-item.info .log-message {
  color: #606266;
}

.log-item.success .log-message {
  color: #67c23a;
}

.log-item.warning .log-message {
  color: #e6a23c;
}

.log-item.error .log-message {
  color: #f56c6c;
}
</style>
